package com.group.three.controller;

import com.github.pagehelper.PageInfo;
import com.group.three.pojo.Person;
import com.group.three.pojo.UserLog;
import com.group.three.pojo.vo.JsonResult;
import com.group.three.service.PersonService;
import com.group.three.service.UserLogService;
import com.group.three.utils.IpUtils;
import com.group.three.utils.SnowFlakeUtil;
import com.group.three.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;
    @Autowired
    private UserLogService userLogService;

    //跳转至user login页面
    @RequestMapping("/tologin")
    public String tologin() {
        return "/2-movie/login";
    }

    //跳转至user login页面
    @RequestMapping("/tologinUser")
    public String tologinUser() {
        return "/2-movie/loginUser";
    }

    //跳转至admin login页面
    @RequestMapping("/toAlogin")
    public String toAlogin() {
        return "/3-admin/login";
    }

    //跳转至user register页面
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "/2-movie/register";
    }

    //跳转至user index页面
    @RequestMapping("/toIndex")
    public String toIndex() {
        return "/2-movie/index";
    }

    //跳转至admin index页面
    @RequestMapping("/toAIndex")
    public String toAIndex() {
        return "/3-admin/index";
    }

    //跳转至/3-admin/admin_add.jsp
    @RequestMapping("/toAdminAdd")
    public String toAdminAdd() {
        return "/3-admin/admin_add";
    }


    //登录
    @RequestMapping("/personLogin")
    @ResponseBody
    public JsonResult personLogin(@RequestParam("personName") String name,
                                  @RequestParam("personPassword") String password,
                                  @RequestParam("personRole") Integer role,
                                  HttpSession session,
                                  HttpServletRequest request) throws Exception {
        String userCode = (String) session.getAttribute("UserCode");
        if (name == null || name.equals("")) {
            return new JsonResult("400", "用户名不能为空");
        }
        if (password == null || "".equals(password)) {
            return new JsonResult("400", "密码不能为空");
        }
        Person person = personService.selectPersonByNameOrEmailOrPhone(name, role);
        if (person == null) {
            return new JsonResult("400", "该用户不存在");
        }
        if (person.getPersonStatus() != 0) {
            return new JsonResult("400", "该账户已经注销或处于冻结状态中");
        }
        if (!password.equals(person.getPersonPassword())) {
            return new JsonResult("400", "用户名密码错误");
        }
        String remoteAddr = request.getRemoteAddr();
        Long id = SnowFlakeUtil.getSnowFlakeId();
        String ipPossession = IpUtils.getIpPossession(remoteAddr);
        LocalDateTime now = LocalDateTime.now();
        userLogService.insertLog(id, person.getPersonId(), remoteAddr, ipPossession,now);
        session.setAttribute("userName", person.getPersonName());
        session.setAttribute("userImage", person.getPersonImage());
        session.setAttribute("userId", person.getPersonId());
        return new JsonResult("200", "登录成功");
    }
    @RequestMapping("/adminLogin")
    @ResponseBody
    public JsonResult adminLogin(@RequestParam("personName") String name,
                                 @RequestParam("personPassword") String password,
                                 @RequestParam("personRole") Integer role,
                                 HttpSession session,
                                 HttpServletRequest request) throws Exception {
        if (name == null || name.equals("")) {
            return new JsonResult("400", "用户名不能为空");
        }
        if (password == null || "".equals(password)) {
            return new JsonResult("400", "密码不能为空");
        }
        Person person = personService.selectPersonByNameOrEmailOrPhone(name, role);
        if (person == null) {
            return new JsonResult("400", "该用户不存在");
        }
        if (person.getPersonStatus() ==3) {
            return new JsonResult("400", "该账户已经被注销");
        }
        if (!password.equals(person.getPersonPassword())) {
            return new JsonResult("400", "用户名密码错误");
        }
        String remoteAddr = request.getRemoteAddr();
        Long id = SnowFlakeUtil.getSnowFlakeId();
        String ipPossession = IpUtils.getIpPossession(remoteAddr);
        LocalDateTime now = LocalDateTime.now();
        userLogService.insertLog(id, person.getPersonId(), remoteAddr, ipPossession,now);
        session.setAttribute("adminName", person.getPersonName());
        session.setAttribute("adminImage", person.getPersonImage());
        session.setAttribute("adminId", person.getPersonId());
        session.setAttribute("adminStatus", person.getPersonStatus());
        return new JsonResult("200", "登录成功");
    }

    //注册
    @RequestMapping("/doRegister")
    @ResponseBody
    public JsonResult doRegister(@RequestParam("personName") String name,
                                 @RequestParam("personEmail") String email,
                                 @RequestParam("personPhone") String phone,
                                 @RequestParam("personPassword") String password,
                                 @RequestParam("personRePassword") String repassword,
                                 @RequestParam("personRole") Integer role) {
        if (name == null || "".equals(name)) {
            return new JsonResult("400", "用户名不能为空");
        }
        if (password == null || "".equals(password)) {
            return new JsonResult("400", "密码不能为空");
        }
        if (repassword == null || "".equals(repassword)) {
            return new JsonResult("400", "确认密码不能为空");
        }
        if (!repassword.equals(password)) {
            return new JsonResult("400", "密码和确认密码不一致");
        }
        Person person = personService.selectPersonByNameOrEmailOrPhone(name, role);
        if (person != null) {
            return new JsonResult("400", "用户名已存在，请修改");
        }
        Long id = SnowFlakeUtil.getSnowFlakeId();
        LocalDateTime now = LocalDateTime.now();
        int register = personService.register(id, name, email, phone, password, role,now );
        if (register != 1) {
            return new JsonResult("400", "注册失败");
        }
        return new JsonResult("200","注册成功");

    }

    //用户退出
    @RequestMapping("/layout")
    public ModelAndView layout(ModelAndView model, HttpSession session) {
        session.invalidate();
        model.setViewName("/2-movie/login");
        return model;
    }

    //管理员退出
    @RequestMapping("/Alayout")
    public ModelAndView Alayout(ModelAndView model, HttpSession session) {
        session.invalidate();
        model.setViewName("/3-admin/login");
        return model;
    }

    //跳转至/2-movie/user.jsp 用户个人中心
    @RequestMapping("/toUserInformation")
    public ModelAndView toUserInformation(ModelAndView model, HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        if (userName == null) {
            model.setViewName("/2-movie/login");
            return model;
        }
        Person person1 = personService.selectPersonByNameOrEmailOrPhone(userName, 0);
        Person person2 = personService.selectPersonByNameOrEmailOrPhone(userName, 2);
        if (person1 != null) {
            model.addObject("personInform", person1);
        } else {
            model.addObject("personInform", person2);
        }
        model.setViewName("/2-movie/user");
        return model;
    }

    //user.jsp保存信息
    @RequestMapping("/toSave")
    @ResponseBody
    public JsonResult toSave(@RequestParam("personName") String name,
                             @RequestParam("personEmail") String email,
                             @RequestParam("personPhone") String phone,
                             @RequestParam("personIntroduction") String introduction,
                             @RequestParam("personRole") Integer role,
                             HttpSession session) throws IOException {
        String userName = (String) session.getAttribute("userName");
        if (userName == null || "".equals(userName)) {
            return new JsonResult("400", "用户未登录");
        }
        Person person = personService.selectPersonByNameOrEmailOrPhone(userName, role);
        int i = personService.updatePerson(person.getPersonId(), name, email, phone, introduction);
        if (i != 1) {
            return new JsonResult("400", "保存失败");
        }
        return new JsonResult("200","保存成功");
    }

    @RequestMapping("/toSaveView")
    @ResponseBody
    public JsonResult toSaveView(@RequestParam("personName") String name,
                                 @RequestParam("personEmail") String email,
                                 @RequestParam("personPhone") String phone,
                                 @RequestParam("personIntroduction") String introduction,
                                 @RequestParam("personId") String id,
                                 HttpSession session) throws IOException {

        int i = personService.updatePerson(Long.valueOf(id), name, email, phone, introduction);
        if (i != 1) {
            return new JsonResult("400", "保存失败");
        }
        return new JsonResult("200","保存成功");
    }

    //用户修改密码页面pwd.jsp跳转
    @RequestMapping("/updatePassword")
    public ModelAndView updatePassword(ModelAndView model, HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        if (userName == null || "".equals(userName)) {
            model.setViewName("/2-movie/login");
            return model;
        }
        Person person1 = personService.selectPersonByNameOrEmailOrPhone(userName, 0);
        Person person2 = personService.selectPersonByNameOrEmailOrPhone(userName, 2);
        if (person1 != null) {
            model.addObject("personPwd", person1);
        } else {
            model.addObject("personPwd", person2);
        }
        model.setViewName("/2-movie/pwd");
        return model;
    }

    //密码修改功能
    @RequestMapping("/saveNewPassword")
    @ResponseBody
    public JsonResult saveNewPassword(@RequestParam("oldPassword") String oldPassword,
                                      @RequestParam("newPassword") String newPassword,
                                      @RequestParam("reNewPassword") String rePassword,
                                      @RequestParam("personRole") Integer role,
                                      HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        Person person = personService.selectPersonByNameOrEmailOrPhone(userName, role);
        if(!oldPassword.equals(person.getPersonPassword())){
            return new JsonResult("400", "旧密码输入不正确");
        }
        if (!newPassword.equals(rePassword)) {
            return new JsonResult("400", "两次新密码输入不一致");
        }
        int i = personService.updatePassword(newPassword, person.getPersonId());
        if (i != 1) {
            return new JsonResult("400", "修改失败");
        }
        session.invalidate();
        return new JsonResult("200", "修改成功");
    }
    //管理员密码修改功能
    @RequestMapping("/saveNewPasswordA")
    @ResponseBody
    public JsonResult saveNewPasswordA(@RequestParam("oldPassword") String oldPassword,
                                       @RequestParam("newPassword") String newPassword,
                                       @RequestParam("reNewPassword") String rePassword,
                                       @RequestParam("personRole") Integer role,
                                       HttpSession session) {
        String userName = (String) session.getAttribute("adminName");
        Person person = personService.selectPersonByNameOrEmailOrPhone(userName, role);
        if(!oldPassword.equals(person.getPersonPassword())){
            return new JsonResult("400", "旧密码输入不正确");
        }
        if (!newPassword.equals(rePassword)) {
            return new JsonResult("400", "两次新密码输入不一致");
        }
        int i = personService.updatePassword(newPassword, person.getPersonId());
        if (i != 1) {
            return new JsonResult("400", "修改失败");
        }
        session.invalidate();
        return new JsonResult("200", "修改成功");
    }

    //跳转至/2-movie/loginlog.jsp页面
    @RequestMapping("/getlogs")
    public ModelAndView getlogs(ModelAndView model, HttpSession session) throws ParseException {
        String userName = (String) session.getAttribute("userName");
        if (userName == null || "".equals(userName)) {
            model.setViewName("/2-movie/login");
            return model;
        }
        Person person1 = personService.selectPersonByNameOrEmailOrPhone(userName, 0);
        Person person2 = personService.selectPersonByNameOrEmailOrPhone(userName, 2);
        PageInfo<UserLog> pageInfo;
        if (person1 != null) {
            pageInfo = userLogService.selectLogsById(1, 10, person1.getPersonId());
        } else {
            pageInfo = userLogService.selectLogsById(1, 10, person2.getPersonId());
        }

        model.addObject("logList", pageInfo);
        model.setViewName("/2-movie/loginlog");
        return model;
    }

    //登录日志页面跳转
    @RequestMapping("/pagelog")
    @ResponseBody
    public JsonResult pagelog(@RequestParam("pageNum") int page,
                              @RequestParam("pageSize") int size,
                              HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        Person person1 = personService.selectPersonByNameOrEmailOrPhone(userName, 0);
        Person person2 = personService.selectPersonByNameOrEmailOrPhone(userName, 2);
        PageInfo<UserLog> pageInfo;
        if (person1!=null){
            pageInfo = userLogService.selectLogsById(page, size, person1.getPersonId());
        } else {
            pageInfo = userLogService.selectLogsById(page, size, person2.getPersonId());
        }
        return new JsonResult(pageInfo);
    }

    //跳转至/3-admin/user_list.jsp页面
    @RequestMapping("/toUserlist")
    public ModelAndView toUserlist(ModelAndView model) {
        PageInfo<Person> pageInfo = personService.selectListByNotRole(1, 10, 1);
        model.addObject("userlist", pageInfo);
        model.setViewName("/3-admin/user_list");
        return model;
    }

    //跳转至/3-admin/admin_list.jsp页面
    @RequestMapping("/toAdminlist")
    public ModelAndView toAdminlist(ModelAndView model) {
        PageInfo<Person> pageInfo = personService.selectListByRole(1, 10, 1);
        model.addObject("adminlist", pageInfo);
        model.setViewName("/3-admin/admin_list");
        return model;
    }

    //admin_list页面翻页功能
    @RequestMapping("/personPage")
    @ResponseBody
    public JsonResult personPage(@RequestParam("pageNum") int page,
                                 @RequestParam("pageSize") int size,
                                 @RequestParam("role") Integer role) {
        PageInfo<Person> pageInfo = personService.selectListByRole(page, size, role);
        return new JsonResult(pageInfo);
    }

    //user_list页面翻页功能
    @RequestMapping("/userPage")
    @ResponseBody
    public JsonResult userPage(@RequestParam("pageNum") int page,
                               @RequestParam("pageSize") int size,
                               @RequestParam("role") Integer role) {
        PageInfo<Person> pageInfo = personService.selectListByNotRole(page, size, role);
        return new JsonResult(pageInfo);
    }

    //user_list.jsp冻结、解冻、删除
    @RequestMapping("/updateStatus")
    @ResponseBody
    public JsonResult updateStatus(@RequestParam("personId") String personId,
                                   @RequestParam("status") Integer status) {
        int i = personService.updateStatusByPersonId(Long.valueOf(personId), status);
        if (i != 1) {
            return new JsonResult("200", "修改失败");
        }
        String msg="";
        if (status==1){
            msg="冻结成功";
        }else if (status==2){
            msg="注销成功";
        }else {
            msg="恢复成功";
        }
        return new JsonResult("200", msg);
    }

    //头像上传并保存到数据库
    @RequestMapping("/upload")
    @ResponseBody
    public JsonResult uploadFile(@RequestParam("image") MultipartFile uploadFile1,
                                 @RequestParam("role") Integer role,
                                 HttpSession session) throws IOException {
        String userName="";
        if (role==1){
            userName = (String) session.getAttribute("adminName");
        }else {
            userName = (String) session.getAttribute("userName");
        }
        Person person = personService.selectPersonByNameOrEmailOrPhone(userName, role);
        //获取上传的文件的文件名
        String fileName = uploadFile1.getOriginalFilename();
        System.out.println("1:" + fileName);
        //处理文件重名问题
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + hzName;
        //获取服务器中photo目录的路径
        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("/resource/static/base/person");
        File file = new File(photoPath);
        if (!file.exists()) {
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + fileName;
        //实现上传功能
        uploadFile1.transferTo(new File(finalPath));
        int i = personService.updateImage(fileName, person.getPersonId());
        if (i != 1) {
            return new JsonResult("400", "上传失败");
        }
        return new JsonResult();
    }

    //普通管理员和超级管理员添加
    @RequestMapping("/adminadd")
    @ResponseBody
    public JsonResult adminadd(@RequestParam("name") String name,
                               @RequestParam("newPassword") String password,
                               @RequestParam("reNewPassword") String repassword,
                               @RequestParam("statues") Integer status,
                               @RequestParam("role") Integer role) {
        if (name == null || "".equals(name)) {
            return new JsonResult("400", "用户名不能为空");
        }
        if (password == null || "".equals(password)) {
            return new JsonResult("400", "密码不能为空");
        }
        if (repassword == null || "".equals(repassword)) {
            return new JsonResult("400", "确认密码不能为空");
        }
        if (!password.equals(repassword)) {
            return new JsonResult("400", "密码与确认密码不一致");
        }
        Person personnext = personService.selectPersonByNameOrEmailOrPhone(name, role);
        if (personnext != null) {
            return new JsonResult("400", "用户名已存在");
        }
        Long id = SnowFlakeUtil.getSnowFlakeId();
        int i = personService.insertAdminRole(id, name, password, role, status);
        if (i != 1) {
            return new JsonResult("400", "管理员创建失败");
        }
        String msg = "";
        if (status == 0) {
            msg = "普通管理员创建成功";
        } else {
            msg = "超级管理员创建成功";
        }
        return new JsonResult("200", msg);
    }

    //跳转至/3-admin/pwd.jsp
    @RequestMapping("/toAdminpwd")
    public ModelAndView toAdminpwd(ModelAndView model, HttpSession session) {
        String userName = (String) session.getAttribute("adminName");
        if (userName == null || "".equals(userName)) {
            model.setViewName("/3-admin/login");
            return model;
        }
        Person person = personService.selectPersonByNameOrEmailOrPhone(userName, 1);
        model.addObject("adminPwd", person.getPersonPassword());
        model.setViewName("/3-admin/pwd");
        return model;
    }

    //admin_list模糊查询
    @RequestMapping("/selectLikeName")
    @ResponseBody
    public JsonResult selectLikeName(@RequestParam("selectName") String name,
                                     @RequestParam("personRole") Integer role) {
        if (name == null || "".equals(name)) {
            return new JsonResult("400", "请输入查询条件");
        }
        PageInfo<Person> pageInfo = personService.selectInformByLikeName(1, 10, name, role);
        return new JsonResult(pageInfo);
    }
    //user_list模糊查询
    @RequestMapping("/selectLikeUserName")
    @ResponseBody
    public JsonResult selectLikeUserName(@RequestParam("selectName") String name,
                                         @RequestParam("personRole") Integer role) {
        if (name == null || "".equals(name)) {
            return new JsonResult("400", "请输入查询条件");
        }
        PageInfo<Person> pageInfo = personService.selectInformByLikeNameNotRole(1, 10, name, role);
        return new JsonResult(pageInfo);
    }

    //admin_list页面模糊查询翻页功能
    @RequestMapping("/personSelectPage")
    @ResponseBody
    public JsonResult personSelectPage(@RequestParam("pageNum") int page,
                                       @RequestParam("pageSize") int size,
                                       @RequestParam("selectName") String name,
                                       @RequestParam("personRole") Integer role) {
        PageInfo<Person> pageInfo = personService.selectInformByLikeName(page, size, name, role);
        return new JsonResult(pageInfo);
    }
    //user_list页面模糊查询翻页功能
    @RequestMapping("/userSelectPage")
    @ResponseBody
    public JsonResult userSelectPage(@RequestParam("pageNum") int page,
                                     @RequestParam("pageSize") int size,
                                     @RequestParam("selectName") String name,
                                     @RequestParam("personRole") Integer role) {
        PageInfo<Person> pageInfo = personService.selectInformByLikeNameNotRole(page, size, name, role);
        return new JsonResult(pageInfo);
    }

    //携带数据跳转至/3-admin/adminloginlog_list.jsp
    @RequestMapping("/toAdminLogs")
    public ModelAndView toAdminLogs(ModelAndView model) {
        PageInfo<Person> pageInfo = personService.selectLogsByRole(1, 10, 1, null);
        model.addObject("adminloglist", pageInfo);
        model.setViewName("/3-admin/adminloginlog_list");
        return model;
    }

    //携带数据跳转至/3-admin/userloginlog_list.jsp
    @RequestMapping("/toUserLogs")
    public ModelAndView toUserLogs(ModelAndView model) {
        PageInfo<Person> pageInfo = personService.selectLogsByRole(1, 10, 0, null);
        model.addObject("userloglist", pageInfo);
        model.setViewName("/3-admin/userloginlog_list");
        return model;
    }

    //实现  /3-admin/adminloginlog_list.jsp 的分页
    @RequestMapping("/logsPageInfo")
    @ResponseBody
    public JsonResult logsPageInfo(@RequestParam("pageNum") int page,
                                   @RequestParam("pageSize") int size,
                                   @RequestParam("role") Integer role,
                                   @RequestParam("Condition") String name) {
        PageInfo<Person> pageInfo = personService.selectLogsByRole(page, size, role, name);
        return new JsonResult(pageInfo);
    }

    //实现  /3-admin/adminloginlog_list.jsp 的分页
    @RequestMapping("/logsPageInfoUser")
    @ResponseBody
    public JsonResult logsPageInfoUser(@RequestParam("pageNum") int page,
                                       @RequestParam("pageSize") int size,
                                       @RequestParam("role") Integer role,
                                       @RequestParam("Condition") String name) {
        PageInfo<Person> pageInfo = personService.selectLogsByNotRole(page, size, role, name);
        return new JsonResult(pageInfo);
    }

    // /3-admin/adminloginlog_list.jsp日志搜索
    @RequestMapping("/logsSelect")
    @ResponseBody
    public JsonResult logsSelect(@RequestParam("pageNum") int page,
                                 @RequestParam("pageSize") int size,
                                 @RequestParam("role") Integer role,
                                 @RequestParam("Condition") String name) {
        PageInfo<Person> pageInfo = personService.selectLogsByRole(page, size, role, name);
        if (pageInfo.getList().size() == 0) {
            return new JsonResult("400", "暂无符合条件的用户");
        }
        return new JsonResult(pageInfo);
    }

    // /3-admin/userloginlog_list.jsp日志搜索
    @RequestMapping("/logsSelectUser")
    @ResponseBody
    public JsonResult logsSelectUser(@RequestParam("pageNum") int page,
                                     @RequestParam("pageSize") int size,
                                     @RequestParam("role") Integer role,
                                     @RequestParam("Condition") String name) {
        PageInfo<Person> pageInfo = personService.selectLogsByNotRole(page, size, role, name);
        if (pageInfo.getList().size() == 0) {
            return new JsonResult("400", "暂无符合条件的用户");
        }
        return new JsonResult(pageInfo);
    }

    //跳转到详细用户界面
    @RequestMapping("/toUserView/{personId}")
    public ModelAndView toUserView(@PathVariable("personId") Long personId, ModelAndView model) {
        Person person = personService.selectInformById(personId);
        model.addObject("personView", person);
        model.setViewName("/3-admin/user_view");
        return model;
    }

}
